﻿using Finance.Infrastructrue.Interface;
using Finance.API.Write.Application.Command.PayableManagementCommand;
using Finance.Domain;
using Finance.ErrorCode;
using MediatR;
using Org.BouncyCastle.Cms;
using AutoMapper;
using System.DirectoryServices.Protocols;
using System.Transactions;
using Finance.Infrastructrue.Implement;

namespace Finance.API.Write.Application.Hander.PayableManagementHander
{
    public class AddPayableManagementHander:IRequestHandler<AddPayableManagementCommand,APIResult<int>>
    {
       
        DatabaseContext db;
        IBaseRepository<PayableManagement> payRep;
        IBaseRepository<FinancialBookkeeping> finRep;
        ILogger<AddPayableManagementHander> logger;
        IMapper mapper;

        public AddPayableManagementHander(DatabaseContext db, IBaseRepository<PayableManagement> payRep, IBaseRepository<FinancialBookkeeping> finRep, ILogger<AddPayableManagementHander> logger, IMapper mapper)
        {
            this.db = db;
            this.payRep = payRep;
            this.finRep = finRep;
            this.logger = logger;
            this.mapper = mapper;
        }

        public  async Task<APIResult<int>> Handle(AddPayableManagementCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            try
            {
               
                    
                    //判断编号是否存在
                    var mls =  db.SqlSugar.Queryable<PayableManagement>().Where(a => !a.IsDel && a.FlowingWaterNumber == request.FlowingWaterNumber).First();

                    if (mls != null)
                    {
                        result.Code = APIEnum.Ok;
                        result.Message = "该编号已存在";

                        return await Task.FromResult(result);
                    }

                    var payable = mapper.Map<PayableManagement>(request);
                    payable.IsDel = false;
                    var m = await db.SqlSugar.Insertable(payable).ExecuteCommandAsync();



                   

                    if (m > 0)
                    {
                        result.Code = APIEnum.Ok;
                        result.Message = "应付管理添加成功";
                        result.Data = m;
                    }
                    else
                    {
                        result.Code = APIEnum.Fail;
                        result.Message = "应付管理添加失败";
                        result.Data = m;
                    }
                    
                

            }
            catch (Exception ex)
            {
                logger.LogError("应付管理添加报错"+ex.Message);
               throw;
            }
            return await Task.FromResult(result);
        }
    }
}
